package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.Excel.ExcelExportService;
import com.example.demo.mapper.OrderMapper;
import com.example.demo.mapper.PutOrderMapper;
import com.example.demo.mapper.StockPositionsMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.Order.Orders;
import com.example.demo.pojo.Order.PutOrders;
import com.example.demo.pojo.Stock.StockPositions;
import com.example.demo.utils.TokenUtil.JwtUtils;
import com.example.demo.utils.TokenUtil.decryptToken;
import com.example.demo.utils.TokenUtil.spiltUtils;
import com.example.demo.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/excels")
public class ExcelExportController {

    @Autowired
    private ExcelExportService excelExportService;
    @Resource
    private UserUtil userUtil;
    @Resource
    private PutOrderMapper putOrderMapper;

    @Resource
    private StockPositionsMapper stockPositionsMapper;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private UserMapper userMapper;

    /**
     * 挂单导出Excel
     *
     * @param orderId 比赛id
     */
    @GetMapping("/exportPutOrders")
    public void exportPutOrders(HttpServletResponse response,
                                @CookieValue(name = "token", required = false) String token,
                                Integer orderId,
                                @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
                                @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime) throws IOException {
        File tempFile = null;
        try {
            // 获取并验证Token
            if (token == null || token.isEmpty() || !JwtUtils.verifyToken(token)) {
                throw new Exception("用户未登录或登录异常");
            }
            // 解密Token以获取用户名
            String decrypt = decryptToken.decrypt(token);
            String userName = spiltUtils.getUserName(decrypt);
            Integer userId = userUtil.getUserId(userName);

            // 根据orderId和userId查询订单，并添加时间范围条件
            QueryWrapper<PutOrders> putOrdersQueryWrapper = new QueryWrapper<>();
            putOrdersQueryWrapper.select("order_code", "stock_code", "order_name", "order_type", "price", "quantity", "unexecuted_quantity", "order_status", "time")
                    .eq("order_id", orderId)
                    .eq("user_id", userId);

            if (startTime != null) {
                putOrdersQueryWrapper.ge("time", startTime);
            }
            if (endTime != null) {
                // 将结束时间设置为那一天的最后一刻
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(endTime);
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                calendar.set(Calendar.MILLISECOND, 999);
                endTime = calendar.getTime();
                putOrdersQueryWrapper.le("time", endTime);
            }
            List<PutOrders> putOrders = putOrderMapper.selectList(putOrdersQueryWrapper);

            // 创建临时文件
            tempFile = File.createTempFile("put_orders_", ".xlsx");

            // 导出数据到临时文件
            excelExportService.exportPutOrders(putOrders, tempFile.getAbsolutePath());

            // 设置响应头
            String fileName = "委托历史订单.xlsx";
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String file = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + file);

            // 从临时文件读取数据并写入响应
            Files.copy(tempFile.toPath(), response.getOutputStream());
        } catch (Exception e) {
            // 异常处理
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出Excel失败");
        } finally {
            // 删除临时文件
            if (tempFile != null) {
                tempFile.delete();
            }
        }
    }

    @GetMapping("/exportPutOrdersNew")
    public void exportPutOrdersNew(HttpServletResponse response,
                                @CookieValue(name = "token", required = false) String token,
                                @RequestParam Integer competitionId,
                                @RequestParam String buyMethod,
                                @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
                                @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime) throws IOException {
        File tempFile = null;
        try {
            // 获取并验证Token
            if (token == null || token.isEmpty() || !JwtUtils.verifyToken(token)) {
                throw new Exception("用户未登录或登录异常");
            }
            // 解密Token以获取用户名
            String decrypt = decryptToken.decrypt(token);
            String userName = spiltUtils.getUserName(decrypt);
            Integer userId = userUtil.getUserId(userName);

            // 根据orderId和userId以及buyMethod查询订单，并添加时间范围条件
            QueryWrapper<Orders> OrdersQueryWrapper = new QueryWrapper<>();
            OrdersQueryWrapper.select( "competition_id","stock_code", "stock_name", "order_type","buy_method", "price", "order_quantity", "finish_quantity","draw_quantity", "order_status", "time")
                    .eq("competition_id", competitionId)
                    .eq("user_id", userId)
                    .eq("buy_method", buyMethod);

            if (startTime != null) {
                OrdersQueryWrapper.ge("time", startTime);
            }
            if (endTime != null) {
                // 将结束时间设置为那一天的最后一刻
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(endTime);
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                calendar.set(Calendar.MILLISECOND, 999);
                endTime = calendar.getTime();
                OrdersQueryWrapper.le("time", endTime);
            }
            List<Orders> Orders = orderMapper.selectList(OrdersQueryWrapper);
            if(Orders.size()==0){
                log.info("没有找到符合类型的订单!");
            }

            // 创建临时文件
            tempFile = File.createTempFile("put_orders_", ".xlsx");

            // 导出数据到临时文件
            excelExportService.exportPutOrdersNew(Orders, tempFile.getAbsolutePath());

            // 设置响应头
            String fileName = "委托历史订单.xlsx";
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String file = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + file);

            // 从临时文件读取数据并写入响应
            Files.copy(tempFile.toPath(), response.getOutputStream());
        } catch (Exception e) {
            // 异常处理
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出Excel失败");
        } finally {
            // 删除临时文件
            if (tempFile != null) {
                tempFile.delete();
            }
        }
    }

    /**
     * 历史订单Excel导出
     *
     * @param orderId   比赛id
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @throws IOException
     */
    @GetMapping("/exportOrders")
    public void exportOrders(HttpServletResponse response,
                             @CookieValue(name = "token", required = false) String token,
                             Integer orderId,
                             @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
                             @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime) throws IOException {
        File tempFile = null;
        try {
            // 获取并验证Token
            if (token == null || token.isEmpty() || !JwtUtils.verifyToken(token)) {
                throw new Exception("用户未登录或登录异常");
            }

            // 解密Token以获取用户名
            String decrypt = decryptToken.decrypt(token);
            String userName = spiltUtils.getUserName(decrypt);
            Integer userId = userUtil.getUserId(userName);

            // 根据orderId和userId查询订单，并添加时间范围条件
            QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
            ordersQueryWrapper.select("stock_code", "stock_name", "order_type", "price", "quantity", "status", "time")
                    .eq("order_id", orderId)
                    .eq("user_id", userId);

            if (startTime != null) {
                ordersQueryWrapper.ge("time", startTime);
            }
            if (endTime != null) {
                // 将结束时间设置为那一天的最后一刻
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(endTime);
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                calendar.set(Calendar.MILLISECOND, 999);
                endTime = calendar.getTime();
                ordersQueryWrapper.le("time", endTime);
            }

            List<Orders> orders = orderMapper.selectList(ordersQueryWrapper);

            // 创建临时文件
            tempFile = File.createTempFile("orders_", ".xlsx");

            // 导出数据到临时文件
            excelExportService.exportOrders(orders, tempFile.getAbsolutePath());

            // 设置响应头
            String fileName = "成交历史订单.xlsx";
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String file = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + file);

            // 从临时文件读取数据并写入响应
            Files.copy(tempFile.toPath(), response.getOutputStream());
        } catch (Exception e) {
            // 异常处理
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出Excel失败");
        } finally {
            // 删除临时文件
            if (tempFile != null) {
                tempFile.delete();
            }
        }
    }

    /**
     * 持仓信息Excel导出
     *
     * @param id 比赛id
     * @throws IOException
     */
    @GetMapping("/exportStockPositions")
    public void exportStockPositions(HttpServletResponse response,
                                     @CookieValue(name = "token", required = false) String token,
                                     Integer id) throws IOException {
        File tempFile = null;
        try {
            // 获取并验证Token
            if (token == null || token.isEmpty() || !JwtUtils.verifyToken(token)) {
                throw new Exception("用户未登录或登录异常");
            }

            // 解密Token以获取用户名
            String decrypt = decryptToken.decrypt(token);
            String userName = spiltUtils.getUserName(decrypt);
            Integer userId = userUtil.getUserId(userName);

            // 根据Id和userId查询持仓
            QueryWrapper<StockPositions> stockPositionsQueryWrapper = new QueryWrapper<>();
            stockPositionsQueryWrapper.select("stock_code", "stock_name", "quantity",
                            "available_quantity", "frozen_quantity",
                            "position_value", "position_profit_loss",
                            "cost_price", "latest_price",
                            "market_value", "profit_loss_ratio",
                            "position_ratio", "market")
                    .eq("position_id", id)
                    .eq("user_id", userId);
            List<StockPositions> stockPositions = stockPositionsMapper.selectList(stockPositionsQueryWrapper);

            // 创建临时文件
            tempFile = File.createTempFile("stockPositions_", ".xlsx");

            // 导出数据到临时文件
            excelExportService.exportStockPositions(stockPositions, tempFile.getAbsolutePath());

            // 设置响应头
            String fileName = "成交持仓信息.xlsx";
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String file = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + file);

            // 从临时文件读取数据并写入响应
            Files.copy(tempFile.toPath(), response.getOutputStream());
        } catch (Exception e) {
            // 异常处理
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出Excel失败");
        } finally {
            // 删除临时文件
            if (tempFile != null) {
                tempFile.delete();
            }
        }
    }

}